<?php
/**
 * (logic) 产品广告
 */
namespace App\Logic\Operation\Ads;

use App\Models\AmazonAds\AdsError;
use App\Models\AmazonAds\SpAdvertisedProduct as SpAdvertisedProductModel;
use App\Models\Basics\SysCountry;
use App\Models\Product\ProductAmazonSku;
use App\Models\Product\ProductSku;
use App\Models\Operation\Ads;

class SpAdvertisedProduct
{
    /**
     * @param $date
     * @return string[]
     */
    public static function exe($date): array
    {
        ini_set('memory_limit', '200M');
        set_time_limit(0);
        if(!array_key_exists('startDate',$date) || !array_key_exists('endDate',$date)){
            return ['_ParseSpAdvertisedProduct' => date('Y-m-d H:i:s').'--date参数不全'];
        }
        $dateStart = $date['startDate'];
        $startTime = strtotime($dateStart);
        $endDate = $date['endDate'];
        $endTime = strtotime($endDate);
        while (true){
            if($startTime > $endTime)break;
            $date = date('Y-m-d',$startTime);
            echo '==========start:'.$date.'========'.PHP_EOL;
            $lines = SpAdvertisedProductModel::query()
                ->selectRaw('countryCode,advertisedSku,
                    sum(impressions) as impressions,
                    sum(clicks) as clicks,
                    sum(spend) as spend,
                    sum(unitsSoldClicks14d) as unitsSoldClicks14d,
                    sum(sales14d) as sales14d')
                ->where('date',$date)
                ->groupBy(['countryCode','advertisedSku'])
                ->get();
            $items = [];
            foreach($lines as $line){
                $key = $line->countryCode.','.$line->advertisedSku;
                $impressions = $line->impressions;
                $clicks = $line->clicks;
                $spend = $line->spend;
                $totalSales = $line->sales14d;
                $totalUnits = $line->unitsSoldClicks14d;
                if(array_key_exists($key,$items)){
                    $items[$key]['impressions'] += $impressions;
                    $items[$key]['clicks'] += $clicks;
                    $items[$key]['spend'] += $spend;
                    $items[$key]['total_sales'] += $totalSales;
                    $items[$key]['total_units'] += $totalUnits;
                }else{
                    $items[$key] = [
                        'impressions' => $impressions,
                        'clicks' => $clicks,
                        'spend' => $spend,
                        'total_sales' => $totalSales,
                        'total_units' => $totalUnits,
                    ];
                }
            }
            sleep(1);
            $sellerSkuArr = [];
            $countryArr = [];
            $skuArr = [];
            $error = [];
            foreach ($items as $key => $item){
                echo '==========start:'.$key.'========'.PHP_EOL;
                list($countryCode,$sellerSku) = explode(',',$key);
                if(!array_key_exists($countryCode,$countryArr)){
                    $countryArr[$countryCode] = SysCountry::getIdByCountry($countryCode);
                }
                $countryId = $countryArr[$countryCode];
                if (!$countryId) continue;
                if(!array_key_exists($sellerSku,$sellerSkuArr)){
                    $sellerSkuArr[$sellerSku] = ProductAmazonSku::getValueByCode($sellerSku,'psku_id');
                }
                $pSkuId = $sellerSkuArr[$sellerSku];
                if(!$pSkuId){
                    $error[$key]['report_date'] = $date;
                    $error[$key]['country_id'] = $countryId;
                    $error[$key]['type'] = AdsError::TYPE_SP;
                    $error[$key]['data'] = json_encode($item);
                    $error[$key]['error_field'] = $sellerSku;
                    $error[$key]['error_message'] = 'ERP未匹配到该平台SKU：'.$sellerSku;
                    $error[$key]['created_at'] = date('Y-m-d H:i:s');
                    $error[$key]['updated_at'] = date('Y-m-d H:i:s');
                    continue;
                }
                if(!array_key_exists($pSkuId,$skuArr)){
                    $skuArr[$pSkuId] = ProductSku::getValueById($pSkuId,'classify_id');
                }
                $classifyId = $skuArr[$pSkuId];
                if(!$classifyId){
                    $error[$key]['report_date'] = $date;
                    $error[$key]['country_id'] = $countryId;
                    $error[$key]['type'] = AdsError::TYPE_SP;
                    $error[$key]['data'] = json_encode($item);
                    $error[$key]['error_field'] = $sellerSku;
                    $error[$key]['error_message'] = 'ERP未匹配到该平台SKU的SKU所属品类：'.$sellerSku;
                    $error[$key]['created_at'] = date('Y-m-d H:i:s');
                    $error[$key]['updated_at'] = date('Y-m-d H:i:s');
                    continue;
                }
                Ads::query()->updateOrCreate(
                    [
                        'report_date' => $date,
                        'country_id' => $countryId,
                        'seller_sku' => $sellerSku
                    ],
                    [
                        'classify_id' => $classifyId,
                        'impressions' => $item['impressions'],
                        'clicks' => $item['clicks'],
                        'total_units' => $item['total_units'],
                        'spend' => round($item['spend'],3),
                        'total_sales' => round($item['total_sales'],3),
                    ]
                );
                echo '==========end:'.$key.'========'.PHP_EOL;
            }
            if (!empty($error)) {
                AdsError::errorRecord($error);
            }
            $startTime += 86400;
            echo '==========end:'.$date.'========'.PHP_EOL;
        }
        return ['_ParseSpAdvertisedProduct' => date('Y-m-d H:i:s').'--解析完成'];
    }
}
